let md5 = require("md5");
let default_tpl = require('./list/default.html');
let row_tpl = require('./list/row.html');
let page_tpl = require('./list/page.html'); 
window.doT = require('./lib/doT');
const JS_URL = document.currentScript.src;

global.QList = window.QList = {
    STATIC: {
        QEditor: './QEditor.js',
    },
    option: {
        target: 'body',
        api_server: '',
        load_url: '/?qlist=load',
        upload_url: '/?qlist=upload',
        toggle_url: '/?qlist=toggle_switch',
        delete_url:'/?qlist=delete',
        callback: '',
        default_avatar: 'data:image/png;base64iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAA1JREFUGFdjiN9R9B8ABYwCiZHUqeYAAAAASUVORK5CYII=',
        cdn_url: '',
        user_link: null,
        dialog: false,
        //base_url是防止合并JS找不到路径
        base_url: '',
        actions: [],
        pk: '',
        filter: false,
        _P_: {},
        total: 0,
        filter_table: '',
        table: '',
        fields: {},
        table_config: {
            thead: false
        }
    },
    url() {
        let Url_Info = this.parseURL(JS_URL),
            _dirs_ = Url_Info['segments'].slice(0, -3);
        return localStorage.getItem('QUrl') || this.option.base_url || Url_Info.protocol + '://' + Url_Info.host + '/' + (_dirs_.join('/'));
    },
    toggleSwitch: function(element, table, id, field) {
        let value = element.checked ? 1 : 0;
        this.ajax(this.option.toggle_url, {
            act: 'toggle_switch',
            table: table,
            mode:this.option.mode,
            id: id,
            field: field,
            value: value
        }, (res) => {
            if (res.code !== 200) {
                // 如果更新失败,将开关状态恢复
                element.checked = !element.checked;
            }
        });
    },
    init(option) {
        option && Object.assign(this.option, option);
        var QUrl = localStorage.getItem('QUrl'), _this = this;

        if (!this.option.base_url && QUrl) {
            this.option.base_url = QUrl;
        }

        if (!$('.qlist-css').length) {
            $('head').append('<link rel="stylesheet" class="qlist-css" href="' + this.url() + '/static/css/qlist.css">');
        }

        window.addEventListener('resize', () => {
            console.log('autoResize');
            _this.autoResize(_this.option.target)
        });

        _this.page = 1;
        _this.filter = {};
        _this.autoResize(_this.option.target);

        $('#data-list').html('');

        _this.load();

        $('body').off('change', '.qlist-filter-item');

        $('body').on('change', '.qlist-filter-item', function () {
            event.preventDefault();
            var value = $('.qlist-filter-item').serializeArray(), data = {};
            $.each(value, function (index, item) {
                data[item.name] = item.value;
            });
            _this.page = 1;
            $('.qlist-table tbody').html('');
            _this.option._P_ = Object.assign(_this.option._P_, data);
            _this.load();
        })
    },
 
    page: 1,
    sort: '',
    list: [],
    loadPage(page) {
        this.page=page;
        $('.qlist-table tbody').html('');
        this.load();
    },
    load() {
        let _this = this;
        this.ajax(this.option.load_url, {
            table: this.option.table,
            params: this.option._P_,
            page: this.page,
            mode: this.option.mode,
            sort: this.sort,
        }, (res) => {
            if (res.data) {
                _this.option.fields = res.data.fields;
                _this.option.total = res.data.total;
                _this.option.pk = res.data.pk;
                _this.option.search_fields = res.data.search_fields;

                if (res.data.search_fields) {
                    for (var i in res.data.search_fields) {
                        var k = res.data.search_fields[i];
                        if (typeof _this.filter[k] == "undefined") {
                            _this.filter[k] = '';
                        }

                    }
                }
                console.log(_this.filter);
                _this.list = res.data.list;
                _this.renderWithNotpl(res.data);
            }
            _this.page++;
        })
    },
    
    renderWithNotpl(data) {
        data.table = this.option.table;
        data.actions = this.option.actions;
        data.table_config = this.option.table_config;
        data._this = this;
        //渲染基础模板
        if ($('.qlist-table').length == 0) {
            $(this.option.target).html(doT.template(default_tpl)(data))
        }

        $(this.option.target + ' .table-' + data.table + ' tbody').html(doT.template(row_tpl)(data));
        $(this.option.target + ' .qlist-page').html(doT.template(page_tpl)(data))

    },
    editRow(row_id, index) {
        let _this = this;
        this.require('QEditor', () => {
            QEditor.dialogEdit(_this.option.table, _this.option.mode, _this.list[index][_this.option.pk], null, {}, _this.option._P_)
        })
    },

    // 在QList对象中添加新方法
    addNewData() {
        let _this = this;
        this.require('QEditor', () => {
            QEditor.dialogEdit(_this.option.table, _this.option.mode, null, null, {}, _this.option._P_)
        });
    },
    deleteRow(row_id, index) {
        let _this = this;
        if (confirm('确定要删除这条记录吗?')) {
            _this.ajax(_this.option.delete_url, {
                act: 'delete',
                table: _this.option.table,
                mode: _this.option.mode,
                id: _this.list[index][_this.option.pk]
            }, (res) => {
                if (res.code === 200) {
                    _this.msg('删除成功', 'success');
                    _this.list.splice(index, 1);
                    $(_this.option.target + ' .table-' + _this.option.table + ' tbody tr').eq(index).remove();
                    _this.option.total--;
                    if (_this.list.length === 0 && _this.page > 1) {
                        _this.loadPage(_this.page - 1);
                    }
                } else {
                    _this.msg(res.msg || '删除失败', 'error');
                }
            });
        }
    },

    ajax: function (url, data, callback, processData, dataType) {

        let _this = this, handle = typeof processData != "undefined" ? processData : true,
            type = typeof data != "object" ? "get" : "post";

        var api_server = this.option['api_server'] || this.url(), _url;

        if (url.indexOf("http") < 0) {
            _url = api_server + url;
        } else {
            _url = url;
        }
        delete data['_'];
        var tmp = Object.keys(data).sort();
        data['_'] = md5(JSON.stringify(tmp));
        console.log(JSON.stringify(tmp), data['_'], data, Object.keys(data));
        dataType = dataType ? dataType : 'json';
        _url = _url.replace(/\/{3,}/gi, "/");
        callback = (typeof callback == "undefined" && typeof data == "function") ? data : callback;

        var option = {
            url: _url,
            xhrFields: {
                withCredentials: true
            },
            data: data,
            dataType: dataType,
            type: type,
            processData: handle,
            // async: false,
            success: function (response, status, xhr) {
                if (
                    response &&
                    typeof response.msg != "undefined" &&
                    response.msg
                ) {
                    let type =
                        response.code !== 200
                            ? "error"
                            : "success";
                    _this.msg(response.msg, type);
                }
                if (_this.isCallback(callback)) {
                    callback(response);
                }
            },
            fail: function (res) {
                console.info('ajax error', JSON.stringify(res));
                _this.msg('请求失败:' + res.statusText, 'error');
            },
            error(res) {
                console.info('ajax error', JSON.stringify(res));
                _this.msg('请求失败,请确认服务器地址' + '是否正确', 'error');
            }
        };

        if (typeof processData === false) {
            option.contentType = false;
        }

        $.ajax(option);
    },
    msg: function (msg, type, callback) {
        let _this = this;
        if (typeof weui != "undefined") {
            weui.toast(msg, {
                duration: 2000,
                extClass: type == 'error' ? 'weui-icon-warn' : 'weui-icon-success-no-circle',
                callback: function () {
                    _this.isCallback(callback) && callback();
                }
            });
            return;
        }

        if (typeof UIkit != "undefined") {
            UIkit.notification({message: msg, status: type == 'success' ? 'success' : 'error'});
            _this.isCallback(callback) && callback();
            return;
        }

        alert(msg);

    },
    isCallback: function (callback) {
        return typeof callback == "function";
    },

    parseURL(url) {
        let a = document.createElement("a");
        a.href = url;
        return {
            source: url,
            protocol: a.protocol.replace(":", ""),
            host: a.hostname,
            port: a.port,
            query: a.search,
            params: (function () {
                let ret = {},
                    seg = a.search.replace(/^\?/, "").split("&"),
                    len = seg.length,
                    i = 0,
                    s;
                for (; i < len; i++) {
                    if (!seg[i]) {
                        continue;
                    }
                    s = seg[i].split("=");
                    ret[s[0]] = s[1];
                }
                return ret;
            })(),
            file: (a.pathname.match(/\/([^\/?#]+)$/i) || [, ""])[1],
            hash: a.hash.replace("#", ""),
            path: a.pathname.replace(/^([^\/])/, "/$1"),
            relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [, ""])[1],
            segments: a.pathname.replace(/^\//, "").split("/"),
        };
    }, scroll(callback, _target) {
        var target = typeof _target == "undefined" ? window : _target, _this = this;

        $(target).off("scroll");

        $(document).on('scroll', target, function () {

            var scrollTop = $(this).scrollTop(), windowHeight = $(this).height(), documentHeight = $(document).height();

            if (scrollTop < 100) {
                return false;
            }
            //scrollTop + windowHeight >= documentHeight

            if (scrollTop + windowHeight + 100 >= documentHeight) {
                console.log('滚动高度', scrollTop, '对象高度', windowHeight, '文档高度', documentHeight, scrollTop + windowHeight + 100)
                // 用户已经滚动到页面底部
                if (callback && _this.isCallback(callback)) {
                    callback();
                }
            }
        });
    },
    autoResize(target) {
        var width = $(target).width()||$(window).width(), css = width < 420 ? 'q-r-s' : 'q-r-m'; 
        
        console.log('target',width);

        if(width>1024){
            return ;
        }
        if (width < 780) {
            $(target).removeClass('q-r-s q-r-m').addClass('qlist-response ' + css)
        } else {
            $(target).removeClass('qlist-response').removeClass('q-r-m q-r-s');
        }
    }
    , require(js, callback) {

        var jses = typeof js == "string" ? [js] : js, _this = this;

        for (var i in jses) {

            var _js = jses[i],
                _js_ = typeof this.STATIC[_js] != "undefined" ?
                    this.STATIC[_js] : '';

            if (_js_ && _js_.indexOf('./') > -1) {
                _js_ = this.url() + '/static/js/' + (_js_.replace('./', ''));
            }


            if (_js_ && typeof window[_js] == "undefined") {

                _js_ && this.loadScript(_js_, function (params) {

                    if (typeof window[_js] == "undefined") {
                        window[_js] = 1;
                    }

                    if (params.index == params.length - 1) {
                        // console.log(jses, jses.length, params.js, '回调')
                        if (_this.isCallback(callback)) {
                            callback();
                        }
                    }
                }, {index: i, length: jses.length, js: _js_});

            } else {
                // console.log(i, jses.length - 1, i === jses.length - 1, _js_)
                if (Number(i) === jses.length - 1) {
                    if (_this.isCallback(callback)) {
                        callback();
                    }
                }
            }
        }
    }, async loadScript(url, callback, params) {
        var script = document.createElement("script");
        script.type = "text/javascript";
        if (typeof (callback) != "undefined") {
            if (script.readyState) {
                script.onreadystatechange = function () {
                    if (script.readyState == "loaded" || script.readyState == "complete") {
                        script.onreadystatechange = null;
                        callback(params);
                    }
                };
            } else {
                script.onload = function () {
                    callback(params);
                };
            }
        }
        script.src = url;
        document.head.appendChild(script);
    }, formatDate: function (time, fmt) {
        if (!time) {
            return '~';
        }
        if (time.toString().indexOf('-') > -1) {
            var date = new Date(time);
        } else {
            var _time = time.toString(),
                timeStr =
                    _time.length === 10
                        ? parseInt(_time) * 1000
                        : parseInt(_time),
                date = new Date(timeStr);
        }
        var _fmt = fmt ? fmt : "yyyy-MM-dd hh:mm:ss";
        if (/(y+)/.test(_fmt)) {
            _fmt = _fmt.replace(
                RegExp.$1,
                (date.getFullYear() + "").substr(4 - RegExp.$1.length)
            );
        }
        let o = {
            "M+": date.getMonth() + 1,
            "d+": date.getDate(),
            "h+": date.getHours(),
            "m+": date.getMinutes(),
            "s+": date.getSeconds(),
        };
        // 遍历这个对象
        for (let k in o) {
            if (new RegExp(`(${k})`).test(_fmt)) {
                let str = o[k] + "";
                _fmt = _fmt.replace(
                    RegExp.$1,
                    RegExp.$1.length === 1
                        ? str
                        : ("00" + str).substr(str.length)
                );
            }
        }
        //let date=new Date(fmt);
        return _fmt;
    }

}
